<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportToExecl">导出</el-button>
          <el-button size="small" type="primary" @click.native="addEmp">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="EmployeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" width="200px">
            <template #default="{row}">
              <img v-fixImg="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="staffPhoto" @click="showCore(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>

              <el-button type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
              <el-button v-if="checkPerms('delUser')" type="text" size="small" @click="delEmp(row.id)">删除</el-button>
            </template>

          </el-table-column></el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSetting.size" @current-change="currChange" />
        </el-row>
      </el-card>
      <Addemp :show-dialog="showDialog" />
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-dialog title="头像二维码" :visible="isShowCore" @close="isShowCore=false">
        <canvas ref="qrcode" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import Employeestype from '@/api/constant/employees'
import Addemp from './components/Addemp.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import Qrcode, { toCanvas } from 'qrcode'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
export default {
  components: { Addemp, AssignRole },

  data() {
    return {
      showBefore: true,
      EmployeeList: [],
      pageSetting: { page: 1, size: 10 },
      total: 0,
      showDialog: false,
      isShowCore: false,
      showRoleDialog: false,
      userId: ''

    }
  },
  async created(id) {
    this.getEmployeeList()
  },
  methods: {

    assignRole(id) {
      this.userId = id
      this.$refs.assignRole.getUserRoleid(id)
      this.showRoleDialog = true
    },
    showCore(imgurl) {
      if (imgurl) {
        this.isShowCore = true
        this.$nextTick(() => {
          toCanvas(Qrcode.toCanvas(this.$refs.qrcode, imgurl))
        })
      }
    },
    async  delEmp(id) {
      await this.$confirm('是否要删除？')
      await delEmployee(id)
      this.$message.success('删除ok')
      this.getEmployeeList()
    },
    async exportToExecl() {
      const { rows } = await getEmployeeList(this.pageSetting)
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      const newEmpList = rows.map(item => {
        return this.ObjectToArr(item, dict)
      })
      console.log(header, newEmpList)
      export_json_to_excel({
        header,
        data: newEmpList
      })
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageSetting)
      this.EmployeeList = rows
      this.total = total
    },
    currChange(newPage) {
      this.pageSetting.page = newPage
      this.getEmployeeList()
    },
    ObjectToArr(uesr, dict) {
      const newuesr = []
      for (const key in dict) {
        const enkey = dict[key]
        const value = uesr[enkey]
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          newuesr.push(formatDate(value))
        } else if (enkey === 'formOfEmployment') {
          const obj = Employeestype.hireType.find(item => Number(item.id) === Number(value))
          newuesr.push(obj ? obj.value : 'unkown')
        } else { newuesr.push(value) }
      }
      return newuesr
    },
    formatEmployment(ow, column, cellValue, index) {
      const obj = Employeestype.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : ''
    },
    addEmp() {
      this.showDialog = true
    }

  }

}
</script>

<style>
.staffPhoto{
width: 180px;
height: 120px;
object-fit: cover;
}
</style>
